/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import event.SendEvent;
import event.StatusEvent;
import net.sf.appia.core.Direction;
import net.sf.appia.core.Event;
import net.sf.appia.core.Layer;
import net.sf.appia.core.events.SendableEvent;
import net.sf.appia.core.events.channel.ChannelClose;
import net.sf.appia.core.events.channel.ChannelInit;
import net.sf.appia.protocols.common.RegisterSocketEvent;
import net.sf.appia.protocols.common.SendableNotDeliveredEvent;
import util.Debug;

/**
 *
 * @author Welington
 */
public class FairLossSession extends CustomSession {

    public FairLossSession(Layer layer) {
        super(layer);
        current = getClass();
    }

    @Override
    public void handle(Event event) {
        if (event instanceof ChannelInit) {
            handleInit((ChannelInit) event);
        } else if (event instanceof ChannelClose) {
            handleCloseChannel((ChannelClose) event);
        } else if (event instanceof RegisterSocketEvent) {
            handleRegisterSocket((RegisterSocketEvent) event);
        } else if (event instanceof SendableNotDeliveredEvent) {
            handleDeliveryError((SendableNotDeliveredEvent) event);
        } else if (event instanceof SendableEvent) {
            handleDeliveryEvent((SendEvent) event);
        } else if (event instanceof SendEvent) {
            if (event.getDir() == Direction.UP)
                handleDeliveryEvent((SendEvent) event);
            else
                handleSendEvent((SendEvent) event);
        }
    }

    @Override
    protected void handleInit(ChannelInit event) {
        debug.print(Debug.LOG, current, "handleInit(ChannelInit event)");
        sendEvent(event);
    }

    private void handleCloseChannel(ChannelClose event) {
        debug.print(Debug.LOG, current, "handleCloseChannel(ChannelClose event)");
        sendEvent(event);
    }

    private void handleRegisterSocket(RegisterSocketEvent event) {
        debug.print(Debug.LOG, current, "handleRegisterSocket(RegisterSocketEvent event)");
        sendEvent(event);
    }

    private void handleDeliveryError(SendableNotDeliveredEvent event) {
        debug.print(Debug.LOG, current, "handleDeliveryError(SendableNotDeliveredEvent event)");

        StatusEvent se = new StatusEvent(StatusEvent.ERROR);
        se.setMessage("Message not delivered");

        se.setChannel(event.getChannel());
        se.setDir(Direction.UP);
        se.setSourceSession(this);
        initEvent(se);
        sendEvent(se);
    }

    private void handleDeliveryEvent(SendEvent event) {
        debug.print(Debug.LOG, current, "handleDeliveryEvent(SendEvent event)");
        sendEvent(event);
    }

    private void handleSendEvent(SendEvent event) {
        debug.print(Debug.LOG, current, "handleSendEvent(SendEvent event)");
        sendEvent(event);
    }
}
